﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace ElectronicCommerce.Framework.Utility
{
    public static class JsonHelper
    {
        /// <summary>
        /// Object to Json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(object obj)
        {
            using (var ms = new MemoryStream())
            {
                var s = new DataContractJsonSerializer(obj.GetType());
                s.WriteObject(ms, obj);

                ms.Seek(0, SeekOrigin.Begin);

                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }

        /// <summary>
        /// Json to Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="searchCondition"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(string jsonData) where T : class, new()
        {
            try
            {
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                    return serializer.ReadObject(ms) as T;
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
